package com.efounder.fragment;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.agency.activity.AgentFgNew;
import com.efounder.chat.adapter.TaskListAdapter;
import com.efounder.chat.model.AppConstant;
import com.efounder.chat.model.Task;
import com.efounder.chat.model.TaskRefreshEvent;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.http.EFHttpRequest;
import com.efounder.ospmobilelib.R;
import com.efounder.util.AbFragmentManager;
import com.pansoft.resmanager.ResFileManager;
import com.pansoft.xmlparse.FormatCol;
import com.pansoft.xmlparse.FormatColTab;
import com.pansoft.xmlparse.FormatRow;
import com.pansoft.xmlparse.FormatRowTab;
import com.pansoft.xmlparse.FormatSet;
import com.pansoft.xmlparse.FormatTable;
import com.pansoft.xmlparse.FormatTableTab;
import com.pansoft.xmlparse.MobileFormatUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 *业务模块中任务的fragment
 *@author slp
 *@date 2018/3/02
 */
@SuppressLint("ValidFragment")
public class BacklogFragment extends BaseFragment {

    private static final String TAG = "BacklogFragment";
    private View root;
    private StubObject mStubObject;
    private StubObject toNextStu;
    //标题栏
    private View viewTitle;
    private TextView tvTitle;
    private String mMenuIconStr;
    private ImageView ivMenuIcon;
    private ImageView ivTitleMore;
    private AgentFgNew mAgentFgNew;
    private AbFragmentManager mAbFragmentManager;

    private static final String resPath = AppConstant.APP_ROOT + "/res/unzip_res/Image/";
    //	private static final String URL = "http://192.168.248.220:58681/GWTServer/OpenAPIService/" +
//			"TJFlowTask?RequestParam={Param:{RESR_STATUS:%27pending%27}}";
    //private static final String URL1 = "http://zsytght.solarsource.cn:9692/ZSYTGHT/OpenAPIService/" +

    // TODO: 17-8-14 共享用下面的链接
    private static final String URL1 = EnvironmentVariable.getProperty("OSPTaskURL", "http://11.11.48.10:10006/BIZPortalServer") + "/OpenAPIService/TJFlowTask?RequestParam=";
    //共享的不分页
    private String URL2 = "{Param:{Product:'BusinessService',RESR_STATUS:'all',LoadType='USER2LIST'";
    //共享不分页
    private static final String URL3 = ",UserName='" + EnvironmentVariable.getUserName() + "'}}";
    private static final int UPDATED = 1;
    private RecyclerView mRecyclerView;
    private boolean hasLoadData = false;
    private int page = 1;//加载任务的页码
    private List<Task> mData;
    private FormatSet formatSet;
    TaskListAdapter adapter;
//    RelativeLayout include;
//    LinearLayout linearLayout;
//    private PullToRefreshScrollView pullToRefreshScrollView;

    private int taskDataItem0, taskDataItem1;//中油铁工的角标
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            getTaskData(false);
        }
    };
    private String status;

    @SuppressLint("ValidFragment")
    public BacklogFragment(StubObject object) {
        this.mStubObject = object;
        status = "BacklogFragment";
    }

    public BacklogFragment() {
        // Required empty public constructor
    }

    public static BacklogFragment newInstance(boolean b, String status) {
        BacklogFragment agentFgNew = new BacklogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("RESR_STATUS", status);
        bundle.putBoolean("IS_ALONE", b);
        agentFgNew.setArguments(bundle);
        return agentFgNew;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        root = inflater.inflate(R.layout.fragment_backlog, container, false);

        viewTitle = root.findViewById(R.id.view_yewu_title);
        tvTitle = (TextView) root.findViewById(R.id.tv_yewu_frag_name);
        ivMenuIcon = (ImageView) root.findViewById(R.id.iv_yewu_frag_icon);
        ivTitleMore = (ImageView) root.findViewById(R.id.iv_yewu_frag_more);

        mAbFragmentManager = new AbFragmentManager(getContext());

        if (null != getArguments()) {
            status = getArguments().getString("RESR_STATUS");
            boolean is_alone = getArguments().getBoolean("IS_ALONE");
            setAlone(is_alone);
            URL2 = "{Param:{Product:'BusinessService',RESR_STATUS:'" + status + "',LoadType='USER2LIST'";
        }

//        pullToRefreshScrollView = (PullToRefreshScrollView) root
//                .findViewById(R.id.pullToRefreshScrollView);
//        pullToRefreshScrollView.setOnRefreshListener(this);
//        //只允许下拉
//        pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
//        include = (RelativeLayout) root.findViewById(R.id.include);
        // 判断fragment是否是单独的
//        if (isAlone()) {
//            include.setVisibility(View.VISIBLE);
//        } else {
//            include.setVisibility(View.GONE);
//        }
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
//        TextView title = (TextView) root.findViewById(R.id.fragmenttitle);
//        title.setText("任务中心");
//        LinearLayout leftbacklayout = (LinearLayout) root
//                .findViewById(R.id.leftbacklayout);
//        leftbacklayout.setVisibility(View.VISIBLE);
//        leftbacklayout.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
////				AgentFgNew.this.getFragmentManager().popBackStack();
//                getActivity().finish();
//            }
//        });
        formatSet = MobileFormatUtil.getInstance().getFormatSet();

        mData = new ArrayList<>();
        //在每次这个页面第一次加载的时候，需要将badgeNum设为0，防止网络问题加载不出数据，但是badgeNum还是之前数据的问题
//        caculateBadgeNum(0 + "");
        getTaskData(false);
//        Button buttonRight = (Button) root.findViewById(R.id.closeButton);
//        buttonRight.setVisibility(View.INVISIBLE);
//        buttonRight.setBackgroundResource(R.drawable.rightmenu);
//        buttonRight.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
//        linearLayout = (LinearLayout) root
//                .findViewById(R.id.fg_new_agent_linear_layout);

        mRecyclerView = (RecyclerView) root.findViewById(R.id.recyclerView);

        super.onCreateView(inflater, container, savedInstanceState);

        adapter = new TaskListAdapter(getActivity(), mData);
        adapter.setOnItemClickLitener(new TaskListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                EnvironmentVariable.setProperty("TaskDetail_FLOW_ID", null);
                EnvironmentVariable.setProperty("task_flowId", mData.get(position).getFlow_id());
                EnvironmentVariable.setProperty("task_header", mData.get(position).getTitle());
                EnvironmentVariable.setProperty("task_avatar", "");
                EnvironmentVariable.setProperty("task_badgeValue", String.valueOf(mData.get(position).getTodoNum()));
                Map<String, Object> map = new HashMap<String, Object>();


                FormatTable hfmt = formatSet.getFormatTableById(mData.get(position).getId());
//                FormatTable ffmt = formatSet.getFormatTableById(mTaskList.get(position).getId() + "_FL");
                FormatTableTab tfmt = formatSet.getFormatTableTabById(mData.get(position).getId() + "_Tab");
                if (null != tfmt) {
                    List<FormatRowTab> formatRowList = tfmt.getFormatRowList();
                    int size = formatRowList.size();
                    if (size > 0) {
                        Object[] ffmtArray = new Object[size];
                        for (int i = 0; i < size; i++) {
                            String index = "";
                            if ((i + 1) < 10) {
                                index = "0" + (i + 1);
                            } else {
                                index = (i + 1) + "";
                            }
                            List<FormatColTab> list = formatRowList.get(i).getList();
                            String dataSetColID = list.get(0).getDataSetColID();
                            FormatTable ffmt;
                            if (null == dataSetColID) {
                                ffmt = formatSet.getFormatTableById(mData.get(position).getId() + "_FL_" + index);
                            } else {
                                ffmt = formatSet.getFormatTableById(dataSetColID);
                            }
//                            FormatTable ffmt = formatSet.getFormatTableById(mTaskList.get(position).getId() + "_FL_" + index);
                            if (null != ffmt) {
                                Map fmt = getFFMT(ffmt);
                                ffmtArray[i] = fmt;
                            } else {
                                setMapValue(map, position);
                                break;
                            }
                        }
                        if (ffmtArray != null) {
                            map.put("ffmt", ffmtArray);
                        } else {
                            map.put("ffmt", null);
                        }
                    } else {
                        setMapValue(map, position);
                    }
                } else {
                    setMapValue(map, position);
                }
//                if (ffmt != null) {
//                    ma("ffmt", getFMT(ffmt));
//                } else {
//                    map.put("ffmt", null);
//                }
                if (hfmt != null) {
                    map.put("hfmt", getFMT(hfmt));
                } else {
//                    map.put("hfmt", null);
                    Toast.makeText(getContext(), "当前业务资源文件尚未配置，请联系管理员", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (tfmt != null) {
                    map.put("tfmt", getFMT_Tab(tfmt));
                } else {
                    map.put("tfmt", null);
                }
                EnvironmentVariable.setPowerMap(map);
                try {
                    Intent intent = new Intent(getActivity(), Class.forName("com.efounder.RNTaskActivity"));
                    startActivity(intent);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        mRecyclerView.setAdapter(adapter);

        return root;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (mStubObject != null) {
            Hashtable stubTable = mStubObject.getStubTable();
//            mGroupId = Integer.valueOf((String) stubTable.get("groupId"));
            if (stubTable.containsKey("caption")) {
                tvTitle.setText((String) stubTable.get("caption"));
            } else {
                viewTitle.setVisibility(View.GONE);
            }
            if (stubTable.containsKey("menuIcon")) {
                mMenuIconStr = "file://" + ResFileManager.IMAGE_DIR + "/" + stubTable.get("menuIcon");
                LXGlideImageLoader.getInstance().displayImage(getContext(), ivMenuIcon, mMenuIconStr, R.drawable.iframe_icon_refresh, R.drawable.iframe_icon_refresh);
            } else {
                viewTitle.setVisibility(View.GONE);

            }
        }
        toNextStu = new StubObject();
        Hashtable<String, String> stuTable = new Hashtable<>();
        stuTable.put("viewType", "display");
        stuTable.put("AndroidShow", "com.efounder.agency.activity.AgentFgWithIndicator");
        toNextStu.setStubTable(stuTable);

        ivTitleMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mAgentFgNew = AgentFgNew.newInstance(true,"aentFgNew");
                try {
                    mAbFragmentManager.startActivity(toNextStu,0,0);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
    }

//    private void caculateBadgeNum(String s1) {
//
////        EnvironmentVariable.setProperty("Badge_Task", s1);
////        EventBus.getDefault().post(new UpdateBadgeViewEvent(-3 + "", (byte) 2));
//        if (null != status) {
//            if (status.equals("processed")) {
//                EnvironmentVariable.setProperty("Badge_Task_Processed", s1);
//            } else {
//                EnvironmentVariable.setProperty("Badge_Task_Pending", s1);
//            }
//        }
//        EventBus.getDefault().post(new UpdateBadgeViewEvent(-3 + "", (byte) 2));
//    }

    private void setMapValue(Map<String, Object> map, int position) {
        FormatTable ffmt = formatSet.getFormatTableById(mData.get(position).getId() + "_FL");
        if (ffmt != null) {
            map.put("ffmt", getFMT(ffmt));
        } else {
            map.put("ffmt", null);
        }
    }

    /**
     * @param fmt
     * @return
     */
    public static Map getFMT(FormatTable fmt) {

        final Map<String, Object> hfmt = new HashMap<>();

        List<FormatRow> rows = fmt.getFormatRowList();
        List<List> colsList = new ArrayList<List>();
        for (int i = 0; i < rows.size(); i++) {
            List<FormatCol> cols = rows.get(i).getList();
            List<Map> colArray = new ArrayList<Map>();

            for (int j = 0; j < cols.size(); j++) {
                Map<String, Object> colum = new HashMap<String, Object>();
                colum.put("caption", cols.get(j).getCaption());
                colum.put("dataSetColID", cols.get(j).getDataSetColID());
                colum.put("columnType", cols.get(j).getColumnType());
                colum.put("numberPrecision", cols.get(j).getNumberPrecision());
                colum.put("textAlign", cols.get(j).getTextAlign());
                colum.put("textFormat", cols.get(j).getTextFormat());
                colum.put("dateFormat", cols.get(j).getDateFormat());
                colum.put("mask", cols.get(j).getMask());

                colArray.add(colum);
            }
            colsList.add(colArray);
        }

        hfmt.put("detailCol", fmt.getDetailCol());
        hfmt.put("detailName", fmt.getDetailName());
        hfmt.put("rows", rows.size());
        hfmt.put("cols", colsList);
        return hfmt;
    }

    /**
     * 请求数据
     *
     * @param paging true表示分页加载，false为刷新
     */
    private void getTaskData(final boolean paging) {
        Log.d("getTaskData", "begin-->");
        EFHttpRequest httpRequest = new EFHttpRequest(TAG);
        httpRequest.setHttpRequestListener(new EFHttpRequest.HttpRequestListener() {
            @Override
            public void onRequestSuccess(int requestCode, String response) {
                if (response.equals("")) {
//                    caculateBadgeNum(getBadgeNum() + "");
//                    pullToRefreshScrollView.onRefreshComplete();
                } else {
                    try {
                        if (!paging) {
                            mData.clear();
                        }
                        JSONObject responseObject = new JSONObject(response);
                        JSONArray taskListArray = responseObject.getJSONArray("TaskList");
                        if (taskListArray != null) {
                            for (int i = 0; i < taskListArray.length(); i++) {
                                Task task = new Task();
                                task.setTitle((taskListArray.getJSONObject(i).getString("FLOW_MC")));
                                task.setIcon((taskListArray.getJSONObject(i).getString("FlowIcon")));
                                try {
                                    task.setInfo((taskListArray.getJSONObject(i).getString("FLOW_DES")));
                                } catch (JSONException e) {
                                    task.setInfo("");
                                }
                                String PFLOW_ID = taskListArray.getJSONObject(i).optString("PFLOW_ID");
                                if (PFLOW_ID != null && !PFLOW_ID.equals("")) {
                                    task.setId(PFLOW_ID);
                                } else {
                                    task.setId(taskListArray.getJSONObject(i).getString("FLOW_ID"));
                                }
                                task.setFlow_id(taskListArray.getJSONObject(i).getString("FLOW_ID"));
                                if (null != status) {
                                    if (status.equals("processed")) {
                                        task.setTodoNum((taskListArray.getJSONObject(i).getInt("TASK_PROCESSED_COUNT")));

                                    } else {
                                        task.setTodoNum((taskListArray.getJSONObject(i).getInt("TASK_PENDING_COUNT")));

                                    }
                                }
//                                task.setTodoNum((taskListArray.getJSONObject(i).getInt("TASK_PENDING_COUNT")));
                                if (mData.size() <= 2) {
                                    mData.add(task);
                                }
                            }
                        }
                        adapter.notifyDataSetChanged();
//                        caculateBadgeNum(getBadgeNum() + "");
//                        pullToRefreshScrollView.onRefreshComplete();
                    } catch (JSONException e) {
                        e.printStackTrace();
                        //ToastUtil.showToast(getActivity(), "没有更多数据了");
//                        if (pullToRefreshScrollView != null) {
//                            pullToRefreshScrollView.onRefreshComplete();
//                        }
                    }
                }
            }

            @Override
            public void onRequestFail(int requestCode, String message) {
                mData.clear();
                adapter.notifyDataSetChanged();
//                caculateBadgeNum(getBadgeNum() + "");
//                pullToRefreshScrollView.onRefreshComplete();
            }
        });
        /**
         * 共享不分页加载
         * */
        String url = URL2 + URL3;
        url = URLEncoder.encode(url);
        httpRequest.httpGet(URL1 + url);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onSolveEventMessage(TaskRefreshEvent event) {
        getTaskData(false);
        //getTGBadgeNum();//中铁工专用，其他请注释掉
    }

    /**
     * @param fmt
     * @return
     */
    public static Map getFFMT(FormatTable fmt) {

        final Map<String, Object> hfmt = new HashMap<>();
        List<FormatRow> rows = fmt.getFormatRowList();
        List<List> colsList = new ArrayList<List>();
        for (int i = 0; i < rows.size(); i++) {
            List<FormatCol> cols = rows.get(i).getList();
            List<Map> colArray = new ArrayList<Map>();
            for (int j = 0; j < cols.size(); j++) {
                Map<String, Object> colum = new HashMap<String, Object>();
                colum.put("caption", cols.get(j).getCaption());
                colum.put("dataSetColID", cols.get(j).getDataSetColID());
                colum.put("columnType", cols.get(j).getColumnType());
                colum.put("numberPrecision", cols.get(j).getNumberPrecision());
                colum.put("textAlign", cols.get(j).getTextAlign());
                colum.put("textFormat", cols.get(j).getTextFormat());
                colum.put("dateFormat", cols.get(j).getDateFormat());
                colum.put("mask", cols.get(j).getMask());

                colArray.add(colum);
            }
            colsList.add(colArray);
        }

        hfmt.put("detailCol", fmt.getDetailCol());
        hfmt.put("detailName", fmt.getDetailName());
        hfmt.put("rows", rows.size());
        hfmt.put("cols", colsList);
        hfmt.put("tableName", fmt.getId());
        hfmt.put("title", fmt.getCaption());
        return hfmt;
    }

    public static Map getFMT_Tab(FormatTableTab fmt) {
        final Map<String, Object> hfmt = new HashMap<>();

        List<FormatRowTab> rows = fmt.getFormatRowList();
        List<List> colsList = new ArrayList<List>();
        for (int i = 0; i < rows.size(); i++) {
            List<FormatColTab> cols = rows.get(i).getList();
            List<Map> colArray = new ArrayList<Map>();

            for (int j = 0; j < cols.size(); j++) {
                Map<String, Object> colum = new HashMap<String, Object>();
                colum.put("tabName", cols.get(j).getTabName());
                colum.put("icon", cols.get(j).getIcon());
                colum.put("selectIcon", cols.get(j).getSelectIcon());
                colum.put("dataSetColID", cols.get(j).getDataSetColID());
                colArray.add(colum);
            }
            colsList.add(colArray);
        }

        hfmt.put("detailCol", fmt.getDetailCol());
        hfmt.put("detailName", fmt.getDetailName());
        hfmt.put("rows", rows.size());
        hfmt.put("cols", colsList);
        hfmt.put("tableName", fmt.getId());
        hfmt.put("title", fmt.getCaption());
        return hfmt;
    }

    /**
     * 获取TG的报销和OA的角标数
     */
    private void getTGBadgeNum() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String className = "sy.petrochina.zsytg.utils.JExterInterface";
                    ClassLoader loader = Thread.currentThread().getContextClassLoader();
                    Class<?> clazz = loader.loadClass(className);
                    Method method = clazz.getMethod("getTodoCountForApp");
                    String ob = (String) method.invoke(clazz.newInstance(), new Object[]{});
                    net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(ob);
                    if (jsonObject.getJSONObject("TaskDataItem0").getString("COUNT_ROW") != null &&
                            !jsonObject.getJSONObject("TaskDataItem0").getString("COUNT_ROW").equals("")) {
                        taskDataItem0 = Integer.valueOf(jsonObject.getJSONObject("TaskDataItem0").getString("COUNT_ROW"));
                        taskDataItem1 = Integer.valueOf(jsonObject.getJSONObject("TaskDataItem1").getString("COUNT_ROW"));
                        Log.d("wwl_test", "获取铁工角标完成");
                    }
                    handler.sendEmptyMessage(0);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (java.lang.InstantiationException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 获取总的角标数量
     *
     * @return 角标数
     */
//    private int getBadgeNum() {
//        int badgeNum = 0;
//        for (int i = 0; i < mData.size(); i++) {
//            badgeNum += mData.get(i).getTodoNum();
//        }
//        return badgeNum;
//    }

//    @Override
//    public void onVisible() {
//        if (!hasLoadData) {
//            linearLayout.setBackgroundResource(R.drawable.write);
//        }
//    }

//    @Override
//    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
//        getTaskData(false);
//        //getTGBadgeNum();//中铁工专用，其他请注释掉
//    }
//
//    @Override
//    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
//        getTaskData(true);
//    }
//
//    @Override
//    public void onTabBottomActivityResult(int requestCode, int resultCode, Intent data) {
//        Log.i("", "-------onTabBottomActivityResult:" + TAG);
//        if (resultCode == Activity.RESULT_OK) {
//        }
//    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
